import enum
import random
from io import StringIO, BytesIO
from fastapi import Query, HTTPException
from fastapi.responses import StreamingResponse
from io import BytesIO
# from docx import Document
# from docx.shared import Inches, Pt
# from docx.enum.text import WD_ALIGN_PARAGRAPH
import pandas as pd

from fastapi import APIRouter

from src.db import db_models
from src.models import question_model

question_router = APIRouter()
better_question_router = APIRouter()


#基础查询
@question_router.get('/questions')
async def get_questions():
    return await db_models.Questions.filter(is_valid=True).all()


#基础id查询
@question_router.get('/questions/{question_id}')
async def get_question(question_id):
    return await db_models.Questions.filter(id=question_id, is_valid=True).first()


#基础新增
@question_router.post('/questions/add')
async def create_question(question: question_model.Question):
    return await db_models.Questions.create(**question.dict())


#基础更新
@question_router.put('/questions/{question_id}')
async def update_question(question_id: int, question: question_model.Question):
    return await db_models.Questions.filter(id=question_id).update(**question.dict())


#基础逻辑删除
@question_router.delete('/questions/del/{question_id}')
async def delete_question(question_id: int):
    return await db_models.Questions.filter(id=question_id).update(is_valid=False)


#补充评价、优化
@question_router.put('/questions/modify/{question_id}', include_in_schema=False)
async def update_question(question_id: int, pingjia: str, youhua: str):
    return await db_models.Questions.filter(id=question_id).update(pingjia=pingjia, youhua=youhua)


class filetype(enum.Enum):
    docx = 'word/docx'
    excel = 'excel'


#题目导出
@question_router.get('/questions/download/')
async def download_questions(ids: str):
    ids = ids.replace('，', ',').replace("'", '')
    id_list = ids.split(',')
    id_list = [int(i) for i in id_list]
    # if ty == filetype.excel:
    questions = await db_models.Questions.filter(id__in=id_list).all().values()
    questions_dict = [dict(q) for q in questions]
    df = pd.DataFrame(questions_dict)
    # 关键步骤：处理带时区的 datetime 列
    for col in df.columns:
        # 判断列是否为 datetime 类型且带时区
        if pd.api.types.is_datetime64tz_dtype(df[col]):
            # 方法1：转换为 UTC 时间并移除时区（推荐）
            df[col] = df[col].dt.tz_convert(None)  # 直接移除时区信息

    excel_buffer = BytesIO()
    # 指定 engine='openpyxl' 用于生成 .xlsx 格式
    df.to_excel(excel_buffer, index=False, engine='openpyxl')
    excel_buffer.seek(0)  # 回到文件开头

    return StreamingResponse(
        excel_buffer,
        # 正确的 Excel MIME 类型
        media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        # 文件名扩展名改为 .xlsx
        headers={"Content-Disposition": "attachment; filename=questions.xlsx"}
    )
    # else:
    #     doc = Document()
    #     questions = await db_models.Questions.filter(id__in=id_list).all().values('id','tigan')
    #     title = doc.add_heading('问题列表', 0)  # 0 表示最高级标题
    #     title.alignment = WD_ALIGN_PARAGRAPH.CENTER  # 居中对齐
    #     for idx, question in enumerate(questions_dict, 1):
    #         # 添加问题编号（二级标题）
    #         doc.add_heading(f'问题 {idx}', level=2)
    #
    #     word_buffer = BytesIO()
    #     doc.save(word_buffer)
    #     word_buffer.seek(0)  # 回到流的开头
    #
    #     # 5. 返回流式响应（浏览器下载）
    #     return StreamingResponse(
    #         word_buffer,
    #         media_type="application/vnd.openxmlformats-officedocument.wordprocessingml.document",
    #         headers={"Content-Disposition": "attachment; filename=questions.docx"}
    #     )


#进阶分页
@better_question_router.get('/better_questions/limit')
async def get_question_limit(number: int):
    offset = (number - 1) * 10
    # 每页限制 10 条记录
    return await db_models.Questions.all().offset(offset).limit(10)


#进阶随机一题
@better_question_router.get('/better_questions/random', summary='随机一题')
async def get_question_random():
    i = random.randint(1, 10)
    bad_question = await db_models.Questions.filter(is_low=False).values('id')
    good_question = await db_models.Questions.filter(is_low=True).values('id')
    if i < 3:
        j = random.randint(0, len(bad_question) - 1)
        return await db_models.Questions.filter(id=bad_question[j]['id']).first()
    else:
        j = random.randint(0, len(good_question) - 1)
        return await db_models.Questions.filter(id=good_question[j]['id']).values()
